//
//  ZqlUsetAccount.swift
//  ZqlSinaWeiBo
//
//  Created by 赵乾龙 on 16/2/18.
//  Copyright © 2016年 Mr.zhao. All rights reserved.
//

import UIKit

class ZqlUsetAccount: NSObject {

    var access_token: String?
    
    var expires_date: NSDate?
    
    //判断用户账号是否过期,普通用户的账号是三天
    var expires_in:NSTimeInterval = 0 {
        didSet{
         expires_date = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    
    var uid:String?
    
    var name:String?
    
    var avatar_large:String?
    
    //通过KVC设置属性初始值
    init(dict:[String :AnyObject]){
        super.init()
        setValuesForKeysWithDictionary(dict)
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
    }
    
    override var description: String{
        let key = ["access_token","expires_in","uid","name","avatar_large","expires_date"]
        let dict = self.dictionaryWithValuesForKeys(key)
        return dict.description
    }
    
    //通过归解档存储用户信息
    //存储数据
    func saveAccount(){
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
//        print(path)
        //调用归档方法
        NSKeyedArchiver.archiveRootObject(self, toFile: path)
    }
    
    //读取数据
    class func loadUserAccount() -> ZqlUsetAccount? {
        let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).last! as NSString).stringByAppendingPathComponent("userAccount.plist")
        if let userAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(path) as? ZqlUsetAccount {
            
            //判断用户的token是否过期
            if userAccount.expires_date?.compare(NSDate()) == NSComparisonResult.OrderedDescending{
                return userAccount
            }
        }
        return nil
    }
    
    //解档
    required init(coder aDecoder: NSCoder){
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
        expires_date = aDecoder.decodeObjectForKey("expires_date") as? NSDate
    }
    
    //归档
    func encodeWithCoder(aCoder: NSCoder)  {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expires_date,forKey: "expires_date")
    }
    
    
    
}
